<?php

class ConfirmChangePasswordForm extends Form
{
	public $NewPasswordMailModule = 'System/Data/Auth';
	public $NewPasswordMailTemplate = 'templates/newpassword.tpl';
	public $NewPasswordMailSubject = 'Your New Password';
	
	public function ConfirmChangePasswordForm()
	{
		parent::__construct();
		
		$this->Name = 'setpassword';
		$this->Title = translate('Set Password');
		$this->ButtonText = translate('Save Password');
	}
	
	public function FormAction()
	{
		if(isset($_GET['key']) && isset($_GET['value']) &&
			$c = ConfirmRequestManager::GetRequest('http://sociorating.com/confirmsetpassword', $_GET['key'], $_GET['value']) )
		{
			$user = $c->param1;
			
			$bean = UserManager::GetUser($user);
			$this->Bean = $bean;
			
			// add controls to section
			$passwordControl = a2o( 'FormControl', array( 'FieldName' => 'password', 'Title' => translate('New Password'), 'IsBound' => false, 'Type' => 'password', 'Validator' => new StringLengthValidator(8) ) );
			$this->Controls[] = $passwordControl;
			$passwordReControl = a2o( 'FormControl', array( 'FieldName' => 'password_re', 'Title' => translate('New Password(re)'), 'IsBound' => false, 'Type' => 'password' ) );
			$this->Controls[] = $passwordReControl;
		
			if( $this->LoadPostData())
			{
				$password = $passwordControl->GetValue( );
				$passwordRe = $passwordReControl->GetValue( );
				
				if($password != '' &&
					$password == $passwordRe)
				{
					// change password
					$bean->passwordsalt = PasswordHasher::GenerateSalt( );
					$bean->passwordhash = PasswordHasher::GenerateHash( $password, $bean->passwordsalt );
					
					R::store($bean);
					R::trash($c);
					
					//log the user in
					session_start();
					$_SESSION['user'] = $bean->login;
					App::$Current->User = $bean->login;
					session_write_close();

					// send email with password
					$to = $bean->fullname . '<' . $bean->email . '>';					
					$mailTemplate = a2o('TemplateLoader', array( 'Module' => $this->NewPasswordMailModule, 'Template' => $this->NewPasswordMailTemplate,
						'User' => $bean->login, 'Password' => $password, 'FullName' => $bean->fullname ) );
					Mail::Send($to, $this->NewPasswordMailSubject, $mailTemplate->GetText());
					//mail($to, $this->NewPasswordMailSubject, $mailTemplate->translate( ));
					//$this->Messages[] = $mailTemplate->translate();
							
					$this->Messages[] = translate('Your password has changed. You will receive a notification email.');
					$this->HideControls = true;
				}
				else
				{
					$this->Messages[] = translate('The new passwords do not match. Password is not changed.');
				}
			}
		}
		else
		{
			$this->Messages[] = translate('There was an error in handling the confirmation request.');
			$this->HideControls = true;
		}		
	}
}
